<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/13
 * Time: 22:14
 */
class db
{

    private $dbtype = 'mysql';             //数据库类型
    private $dbhost = '';    //数据库地址
    private $dbname = '';          //数据库名字
    private $dbroot = 'root';              //数据库账号
    private $dbpawd = '';  //数据库密码
    private $dbpro = '3306';               //数据库端口
    private $table = '';                   //表名
    private $where = '';                   //条件
    private $pdo = '';                     //数据库句柄
    public static $db = '';                //数据库对象


    /**
     * 连接数据库
     * @param $config [数据库配置参数]
     * @return object [返回句柄对象]
     */
    public function __construct($config = [])
    {
        if (!empty($config['dbhost']) && !empty($config['dbname']) && !empty($config['dbroot'])) {
            $this->dbhost = $config['dbhost'];
            $this->dbname = $config['dbname'];
            $this->dbroot = $config['dbroot'];
            if (!empty($config['dbpawd'])) {
                $this->dbpawd = $config['dbpawd'];
            }

            if (!empty($config['dbpro'])) {
                $this->dbpro = $config['dbpro'];
            }

        }else{
            var_dump('1');
        }
        $dsn = "$this->dbtype:host=$this->dbhost;dbname=$this->dbname";
        $PDO = new PDO($dsn, $this->dbroot, $this->dbpawd);

        if (!$PDO) {
            throw new Exception('无法连接数据库');
        }

        $this->pdo = $PDO;

    }

    /**
     * 选择数据库表 并创建对象
     * @param $table [表名]
     * @return object 返回对象
     */
    public static function Table($table)
    {
        if (empty(self::$db)) {
            self::$db = new self();
        }

        self::$db->connect();
        self::$db->table = $table;

        return self::$db;
    }


    /**
     * 条件
     * @return array 查询单条语句
     */
    public function find($table, $field, $where)
    {
        if (empty($where)) {
            return false;
        }
        $SQL = 'SELECT  ' . $field . ' FROM ' . $table . ' where ' . $where . ' limit 1';

        return $this->pdo->query($SQL)->fetchAll()[0];
    }

    /**
     * 条件
     * @return array 查询多条语句
     */
    public function select($table, $field, $where, $num = null)
    {
        if (empty($where)) {
            return false;
        }
        if (!empty($where) && !empty($num)) {
            $sql = 'SELECT  ' . $field . ' FROM ' . $table . ' where ' . $where . ' limit ' . $num;
        } else if (!empty($where) && empty($num)) {
            $sql = 'SELECT  ' . $field . ' FROM ' . $table . ' where ' . $where;
        } else if (empty($where) && empty($num)) {
            $sql = 'SELECT ' . $field . ' FROM ' . $table;
        }

        return $this->pdo->query($sql)->fetchAll();
    }

    /**
     * 修改操作
     * @return int 受影响的行数
     *
     */
    public function update($table, $params = array(), $where = null)
    {
        $_implode_field = '';
        $_implode_field_arr = array();
        if ( empty($where) ) {       return false;     }
        $where=' WHERE '.$where;
        $fields = array_keys($params);
        foreach ($fields as $key) {
            $_implode_field_arr[] = $key . '=' . ':' . $key;
        }
        $_implode_field = implode(',', $_implode_field_arr);
        $sql = 'UPDATE ' . $table . ' SET ' . $_implode_field  . $where;
        try {
            $stm = $this->pdo->prepare($sql);
            $result = $stm->execute($params);
            return $result;
        } catch (Exception $e) {
            $this->outputError($e->getMessage());
        }
    }

    /**
     * 插入操作
     * @return int
     *
     */
    public function insert($table, $params = array(), $where = null)
    {

        $_implode_field = '';
        $fields = array_keys($params);
        $_implode_field = implode(',', $fields);
        $_implode_value = '';
        foreach ($fields as $value) {
            $_implode_value .= ':' . $value . ',';
        }
        $_implode_value = trim($_implode_value, ',');
        $sql = 'INSERT INTO ' . $table . '(' . $_implode_field . ') VALUES (' . $_implode_value . ')';
        try {
            $stm = $this->pdo->prepare($sql);
            $result = $stm->execute($params);
            return $result;
        } catch (Exception $e) {
            $this->outputError($e->getMessage());
        }
    }

    private function outputError($strErrMsg)
    {
        throw new Exception("MySQL Error: " . $strErrMsg);
    }

    public function __destruct()
    {
        $this->pdo = null;
    }
}